<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" import="Connect.*,java.util.Date"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<title>Hammer Time Auctions</title>
</head>
<body>
	<div id="content">
		<%@include file="header.jsp"%>
		<h1>Success</h1>
		<hr></hr>
		<%
			// Retrieve user input.
			String item_id = request.getParameter("item_id");
			String minimum_bid = request.getParameter("minimum_bid");
			String reserve_price = request.getParameter("reserve_price");
			String bid_increment = request.getParameter("bid_increment");
			String end_date = request.getParameter("end_date");

			// Validate inputs.
			boolean minimum_bid_test = true;
			try {
				// Test if minimum bid is a non-negative double.
				double num = Double.parseDouble(minimum_bid);
				if (num < 0) {
					minimum_bid_test = false;
				}
			} catch (Exception e) {
				minimum_bid_test = false;
			}
			boolean reserve_price_test = true;
			try {
				// Test if reserve price is a non-negative double larger than or equal to minimum bid.
				double num = Double.parseDouble(reserve_price);
				if (num < 0/*Double.parseDouble(minimum_bid)*/) {
					reserve_price_test = false;
				}
			} catch (Exception e) {
				reserve_price_test = false;
			}
			boolean bid_increment_test = true;
			try {
				// Test if bid increment is a non-negative double.
				double num = Double.parseDouble(bid_increment);
				if (num < 0) {
					bid_increment_test = false;
				}
			} catch (Exception e) {
				bid_increment_test = false;
			}
			boolean end_date_test = true;
			try {
				Date end = java.sql.Date.valueOf(end_date);
				Date today = new Date();
				long diff = (end.getTime() - today.getTime()) / (1000 * 60 * 60 * 24);
				if (diff != 2 && diff != 4 && diff != 6) {
					end_date_test = false;
				}
			} catch (Exception e) {
				end_date_test = false;
			}

			// Compile the error messages together.
			String errors = "";
			if (!minimum_bid_test) {
				errors += "* Minimum bid must be a non-negative double.<br />";
			}
			if (!reserve_price_test) {
				errors += "* Reserve price must be a non-negative double larger than or equal to 0.<br />";
			}
			if (!bid_increment_test) {
				errors += "* Bid increment must be a non-negative double.<br />";
			}
			if (!end_date_test) {
				errors += "* End date must be in the yyyy-mm-dd format and 3, 5, or 7 days from today.<br />";
			}

			// If there are any errors return to the creation page with the list of errors and save the submitted data.
			if (!errors.equals("")) {
				session.setAttribute("register_errors", errors);
				session.setAttribute("item_id", item_id);
				session.setAttribute("minimum_bid", minimum_bid);
				session.setAttribute("bid_increment", bid_increment);
				session.setAttribute("reserve_price", reserve_price);
				session.setAttribute("end_date", end_date);
				response.sendRedirect("create_auction.jsp");
			} else {
				// Getting information and updating the database.
				java.sql.Connection conn = null;
				try {
					// Connect to the database.
					Class.forName(ConnectionInfo.myJDBCDriver()).newInstance();
					java.util.Properties sysprops = System.getProperties();
					sysprops.put("user", ConnectionInfo.myUserID());
					sysprops.put("password", ConnectionInfo.myPassword());
					conn = java.sql.DriverManager.getConnection(ConnectionInfo.myURL(), sysprops);

					java.sql.Statement statement = conn.createStatement();
					// Get the username of the customer.
					String owner = (String) session.getAttribute("logged_user");
					// Determine which employee should be assigned to the auction.
					java.sql.ResultSet rs = statement
							.executeQuery("SELECT username, monitor, COUNT(*) AS 'count' FROM (auctions RIGHT JOIN employees ON monitor=username) GROUP BY username ORDER BY count ASC");
					//out.println(rs.getString(1) + "," + rs.getString(2) + "," + rs.getString(3) + "<br/>");
					String monitor = null;
					while (rs.next()) {
						// Check for employees that have no auctions assigned to them.
						if (rs.getString("monitor") == null) {
							monitor = rs.getString("username");
							break;
						}
					}
					if (monitor == null) {
						// Assign this auction to the employee with the least auctioins assinged to them.
						rs.beforeFirst();
						rs.next();
						monitor = rs.getString("username");
					}
					// Insert auction into database.
					String values = "'" + 0 + "','" + item_id + "','" + minimum_bid + "','" + bid_increment + "','" + reserve_price + "'," + "NOW()"
							+ ",'" + end_date + "','" + monitor + "','" + owner + "'";
					statement
							.executeUpdate("INSERT INTO auctions(id, item, minimum_bid, bid_increment, reserve_price, open_date, end_date, monitor, owner)"
									+ "VALUES (" + values + ")");
					// Increment the copies available.
					statement.executeUpdate("UPDATE items SET copies_available=copies_available+1 WHERE id='" + item_id + "'");

					// Set the item_id for view auctions page.
					session.setAttribute("item_id", item_id);
					
					// Redirect the user after adding the item. Clear the form_type variable.
					out.println("New auction created! You will be redirected in 5 seconds.<br />");
					out.println("<a href=\"view_auctions.jsp\">Click here if you can't wait!</a>");
					response.setHeader("Refresh", "5; view_auctions.jsp");
				} catch (Exception e) {
					e.printStackTrace();
					out.print(e.toString());
				} finally {
					try {
						conn.close();
					} catch (Exception ee) {
					}
				}
			}
		%>
	</div>
	<hr></hr>
	<%@include file="footer.jsp"%>
</body>
</html>